package com.cavedroid;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

public class CubeDrawer {
	
	private static final int NUMBER_OF_TRI_VERTICES = 36;
	
	private static final int NUMBER_OF_OUTLINE_VERTICES = 24;
	
	private ByteBuffer triByteBuffer;
	
	private FloatBuffer triBuffer;
	
	private ByteBuffer outlineByteBuffer;
	
	private FloatBuffer outlineBuffer;
	
	public CubeDrawer() {
		float[] triArray = {-0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f,
	 			 -0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f,
				 
	 			 -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f,
	 			 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f,
	 
	 			 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f,
	 			 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f,
	 
	 			 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f,
	 			 -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f,
	 
	 			 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f,
	 			 -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f,
	 
	 			 -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f,
	 			 -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f};
		
		float[] outlineArray = {-0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f,
				  -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f,
				  -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f,
				  0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f,
				  0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f,
				  -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f,
				  -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f,
				  -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f,
				  -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f,
				  0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f,
				  0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f,
				  -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f};
		
		triByteBuffer = ByteBuffer.allocateDirect(triArray.length*(Float.SIZE/8));
		triByteBuffer.order(ByteOrder.nativeOrder());
		triBuffer = triByteBuffer.asFloatBuffer();
		
		for (int i = 0; i < triArray.length; i++) {
			triBuffer.put(i, triArray[i]);
		}
		
		outlineByteBuffer = ByteBuffer.allocateDirect(outlineArray.length*(Float.SIZE/8));
		outlineByteBuffer.order(ByteOrder.nativeOrder());
		outlineBuffer = outlineByteBuffer.asFloatBuffer();
		
		for (int i = 0; i < outlineArray.length; i++) {
			outlineBuffer.put(i, outlineArray[i]);
		}
	}
	
	public void draw(GL10 gl) {
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, triBuffer);
		gl.glDrawArrays(GL10.GL_TRIANGLES, 0, NUMBER_OF_TRI_VERTICES);
		gl.glColor4f(0,0,0,1);
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0 , outlineBuffer);
		gl.glDrawArrays(GL10.GL_LINES, 0, NUMBER_OF_OUTLINE_VERTICES);
	}
}
